// ==================== 配置区域 ====================
// 轮播图配置
const carouselImages = [
    './images/离人泪1.jpg',
    './images/离人泪2.jpg',
    './images/离人泪描述.jpg'
];

// 接口配置
const API_CONFIG = {
    baseUrl: 'http://119.91.237.179:8091/api/v1/gbm',
    endpoints: {
        queryMarketConfig: '/index/query_group_buy_market_config',
        lockPayOrder: '/trade/lock_market_pay_order',
        settlementOrder: '/trade/settlement_market_pay_order'
    }
};

// 业务参数配置
const BUSINESS_PARAMS = {
    source: 's01',
    channel: 'c01',
    goodsId: '9890002',
    notifyUrl: 'http://119.91.237.179:8091/api/v1/test/group_buy_notify'
};

// 全局数据存储
let globalData = {
    goods: null,
    teamList: null,
    currentOrderInfo: null // 存储当前下单信息
};

// ==================== Cookie 操作工具 ====================
const CookieManager = {
    // 设置 Cookie
    set(name, value, days = 7) {
        const date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        const expires = "expires=" + date.toUTCString();
        document.cookie = name + "=" + JSON.stringify(value) + ";" + expires + ";path=/";
    },

    // 获取 Cookie
    get(name) {
        const nameEQ = name + "=";
        const ca = document.cookie.split(';');
        for(let i = 0; i < ca.length; i++) {
            let c = ca[i];
            while (c.charAt(0) == ' ') c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) == 0) {
                try {
                    return JSON.parse(c.substring(nameEQ.length, c.length));
                } catch(e) {
                    return null;
                }
            }
        }
        return null;
    },

    // 删除 Cookie
    delete(name) {
        document.cookie = name + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
    }
};

// ==================== 登录管理 ====================
const LoginManager = {
    // 检查是否已登录
    isLoggedIn() {
        const userInfo = CookieManager.get('userInfo');
        return userInfo !== null && userInfo.userId; // 检查 userId 是否存在
    },

    // 获取用户ID
    getUserId() {
        const userInfo = CookieManager.get('userInfo');
        return userInfo ? userInfo.userId : null;
    },

    // 获取用户信息
    getUserInfo() {
        return CookieManager.get('userInfo');
    },

    // 跳转到登录页
    redirectToLogin() {
        // 获取当前页面的完整URL
        const currentUrl = window.location.href;
        // 跳转到登录页，并传递 redirect 参数
        window.location.href = `login.html?redirect=${encodeURIComponent(currentUrl)}`;
    }
};

// ==================== 需要登录的操作处理 ====================
function requireLogin(action) {
    if (LoginManager.isLoggedIn()) {
        const userId = LoginManager.getUserId();
        console.log('用户已登录:', userId);
        action(userId);
    } else {
        console.log('用户未登录，跳转到登录页');
        LoginManager.redirectToLogin();
    }
}

// ==================== 工具函数 ====================
// 生成12位随机数字
function generateOutTradeNo() {
    return Math.floor(100000000000 + Math.random() * 900000000000).toString();
}

// 显示提示弹窗
function showAlert(message) {
    alert(message);
}

// ==================== API 调用 ====================
const API = {
    // 获取商品页信息
    async queryMarketConfig(userId = null) {
        const params = {
            source: BUSINESS_PARAMS.source,
            channel: BUSINESS_PARAMS.channel,
            goodsId: BUSINESS_PARAMS.goodsId
        };

        // 只有用户登录时才传userId
        if (userId) {
            params.userId = userId;
        }

        try {
            const response = await fetch(API_CONFIG.baseUrl + API_CONFIG.endpoints.queryMarketConfig, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(params)
            });

            const result = await response.json();

            if (result.code === '0000') {
                return result.data;
            } else {
                throw new Error(result.info || '获取商品信息失败');
            }
        } catch (error) {
            console.error('获取商品信息失败:', error);
            showAlert('获取商品信息失败: ' + error.message);
            return null;
        }
    },

    // 拼团下单
    async lockPayOrder(userId, options = {}) {
        // options 可以包含: outTradeNo, teamId
        const { outTradeNo = null, teamId = null } = options;

        // 检查activityId
        if (!globalData.goods || !globalData.goods.activityId) {
            showAlert('该商品暂无团购活动，无法拼团购买');
            return null;
        }

        const params = {
            userId: userId,
            activityId: globalData.goods.activityId,
            source: BUSINESS_PARAMS.source,
            channel: BUSINESS_PARAMS.channel,
            goodsId: BUSINESS_PARAMS.goodsId,
            outTradeNo: generateOutTradeNo(),
            notifyUrl: BUSINESS_PARAMS.notifyUrl
        };

        // 如果有 teamId，说明是参与已有拼团
        if (teamId) {
            params.teamId = teamId;
            console.log(`参与已有拼团，teamId: ${teamId}`);
        } else {
            console.log('发起新的拼团');
        }

        try {
            const response = await fetch(API_CONFIG.baseUrl + API_CONFIG.endpoints.lockPayOrder, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(params)
            });

            const result = await response.json();

            if (result.code === '0000') {
                // 保存订单信息和outTradeNo
                globalData.currentOrderInfo = {
                    ...result.data,
                    outTradeNo: params.outTradeNo,
                    userId: userId
                };
                return result.data;
            } else {
                throw new Error(result.info || '下单失败');
            }
        } catch (error) {
            console.error('拼团下单失败:', error);
            showAlert('拼团下单失败: ' + error.message);
            return null;
        }
    },

    // 交易结算
    async settlementOrder() {
        if (!globalData.currentOrderInfo) {
            showAlert('订单信息不存在');
            return null;
        }

        const params = {
            source: BUSINESS_PARAMS.source,
            channel: BUSINESS_PARAMS.channel,
            outTradeNo: globalData.currentOrderInfo.outTradeNo,
            userId: globalData.currentOrderInfo.userId
        };

        try {
            const response = await fetch(API_CONFIG.baseUrl + API_CONFIG.endpoints.settlementOrder, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(params)
            });

            const result = await response.json();

            if (result.code === '0000') {
                return result.data;
            } else {
                throw new Error(result.info || '支付失败');
            }
        } catch (error) {
            console.error('交易结算失败:', error);
            showAlert('交易结算失败: ' + error.message);
            return null;
        }
    }
};

// ==================== 页面初始化 ====================
// 加载并渲染商品信息
async function loadAndRenderProductInfo() {
    // 获取用户ID（如果已登录）
    const userId = LoginManager.getUserId();
    const data = await API.queryMarketConfig(userId);

    if (!data) {
        return;
    }

    // 保存数据到全局
    globalData.goods = data.goods;
    globalData.teamList = data.teamList;

    // 渲染商品信息
    renderProductInfo();

    // 渲染团购列表
    renderGroupBuyList();
}

// 渲染商品信息
function renderProductInfo() {
    if (!globalData.goods) {
        return;
    }

    const goods = globalData.goods;
    const isLoggedIn = LoginManager.isLoggedIn();

    document.getElementById('productTitle').textContent = goods.goodsName || '商品名称';
    document.getElementById('discountPrice').textContent = `¥${(goods.deductionPrice || 0).toFixed(2)}`;
    document.getElementById('originalPrice').textContent = `¥${(goods.originalPrice || 0).toFixed(2)}`;

    // 显示/隐藏登录提示
    const loginTip = document.getElementById('loginTip');
    if (!isLoggedIn) {
        loginTip.style.display = 'block';
    } else {
        loginTip.style.display = 'none';
    }

    // 更新底部按钮文案
    document.getElementById('buyAloneBtn').textContent = `单独购买(¥${(goods.originalPrice || 0).toFixed(2)})`;
    document.getElementById('buyGroupBtn').textContent = `拼团购买(¥${(goods.deductionPrice || 0).toFixed(2)})`;
}

// 渲染团购列表
function renderGroupBuyList() {
    const container = document.getElementById('groupBuySection');
    container.innerHTML = '';

    // 如果没有团购列表
    if (!globalData.teamList || globalData.teamList.length === 0) {
        container.innerHTML = `
            <div class="empty-team-card">
                <div class="empty-team-text">当前商品暂无拼团组队，快发起团购吧！</div>
            </div>
        `;
        return;
    }

    globalData.teamList.forEach((group, index) => {
        const remainingCount = group.targetCount - group.lockCount;
        const isEnded = group.validTimeCountdown === '已结束' || group.validTimeCountdown === '无效的时间';

        const groupItem = document.createElement('div');
        groupItem.className = 'group-buy-item';

        // 根据是否结束显示不同的内容
        if (isEnded) {
            groupItem.innerHTML = `
              <div class="group-leader">
                  <div class="leader-info">
                      <div class="leader-name">${group.userId}</div>
                      <div class="group-status">
                          <span class="status-text">拼团组队已结束</span>
                          <span class="countdown ended">${group.validTimeCountdown}</span>
                      </div>
                  </div>
              </div>
              <button class="join-group-btn" disabled style="background-color: #ccc; cursor: not-allowed;">参与拼团</button>
            `;
        } else {
            groupItem.innerHTML = `
              <div class="group-leader">
                  <div class="leader-info">
                      <div class="leader-name">${group.userId}</div>
                      <div class="group-status">
                          <span class="status-text">拼团中，组队仅剩<span class="remaining-count">${remainingCount}</span>人，拼团即将结束</span>
                          <span class="countdown" data-countdown="${group.validTimeCountdown}" data-index="${index}">${group.validTimeCountdown}</span>
                      </div>
                  </div>
              </div>
              <button class="join-group-btn" 
                      data-out-trade-no="${group.outTradeNo}" 
                      data-team-id="${group.teamId}">参与拼团</button>
            `;
        }

        container.appendChild(groupItem);
    });

    // 初始化倒计时（只初始化未结束的）
    initCountdowns();
}

// ==================== 轮播图功能 ====================
class Carousel {
    constructor() {
        this.track = document.getElementById('carouselTrack');
        this.indicatorsContainer = document.getElementById('carouselIndicators');
        this.currentIndex = 0;
        this.autoPlayInterval = null;
        this.items = [];
        this.indicators = [];

        this.init();
    }

    init() {
        this.createCarouselItems();
        this.createIndicators();
        this.startAutoPlay();
    }

    createCarouselItems() {
        this.track.innerHTML = '';
        carouselImages.forEach((imgSrc, index) => {
            const item = document.createElement('div');
            item.className = `carousel-item ${index === 0 ? 'active' : ''}`;
            item.innerHTML = `<img src="${imgSrc}" alt="商品图片${index + 1}">`;
            this.track.appendChild(item);
        });
        this.items = this.track.querySelectorAll('.carousel-item');
    }

    createIndicators() {
        this.indicatorsContainer.innerHTML = '';
        carouselImages.forEach((_, index) => {
            const indicator = document.createElement('div');
            indicator.className = `indicator ${index === 0 ? 'active' : ''}`;
            indicator.addEventListener('click', () => this.goToSlide(index));
            this.indicatorsContainer.appendChild(indicator);
        });
        this.indicators = this.indicatorsContainer.querySelectorAll('.indicator');
    }

    goToSlide(index) {
        this.items[this.currentIndex].classList.remove('active');
        this.indicators[this.currentIndex].classList.remove('active');

        this.currentIndex = index;

        this.items[this.currentIndex].classList.add('active');
        this.indicators[this.currentIndex].classList.add('active');
    }

    nextSlide() {
        const nextIndex = (this.currentIndex + 1) % this.items.length;
        this.goToSlide(nextIndex);
    }

    startAutoPlay() {
        this.autoPlayInterval = setInterval(() => {
            this.nextSlide();
        }, 3000);
    }

    stopAutoPlay() {
        if (this.autoPlayInterval) {
            clearInterval(this.autoPlayInterval);
        }
    }
}

// ==================== 倒计时功能 ====================
class CountdownTimer {
    constructor(element, countdownStr, index) {
        this.element = element;
        this.countdownStr = countdownStr; // 格式: "HH:MM:SS"
        this.index = index;
        this.timer = null;

        // 检查是否为特殊状态
        if (countdownStr === '已结束' || countdownStr === '无效的时间') {
            this.element.textContent = countdownStr;
            this.element.classList.add('ended');
            return;
        }

        this.remainingSeconds = this.parseCountdown(countdownStr);

        // 如果解析后的秒数 <= 0，直接显示已结束
        if (this.remainingSeconds <= 0) {
            this.element.textContent = '已结束';
            this.element.classList.add('ended');
            return;
        }

        this.start();
    }

    parseCountdown(countdownStr) {
        // 检查是否为特殊状态字符串
        if (countdownStr === '已结束' || countdownStr === '无效的时间') {
            return 0;
        }

        const parts = countdownStr.split(':');
        if (parts.length === 3) {
            const hours = parseInt(parts[0]) || 0;
            const minutes = parseInt(parts[1]) || 0;
            const seconds = parseInt(parts[2]) || 0;
            return hours * 3600 + minutes * 60 + seconds;
        }
        return 0;
    }

    formatTime(seconds) {
        if (seconds <= 0) return '已结束';

        const hours = Math.floor(seconds / 3600);
        const minutes = Math.floor((seconds % 3600) / 60);
        const secs = seconds % 60;

        return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(secs).padStart(2, '0')}`;
    }

    start() {
        this.update();
        this.timer = setInterval(() => {
            this.remainingSeconds--;
            if (this.remainingSeconds <= 0) {
                this.stop();
                this.element.textContent = '已结束';
                this.element.classList.add('ended');

                // 禁用对应的按钮
                this.disableJoinButton();
            } else {
                this.update();
            }
        }, 1000);
    }

    update() {
        this.element.textContent = this.formatTime(this.remainingSeconds);
    }

    stop() {
        if (this.timer) {
            clearInterval(this.timer);
        }
    }

    // 禁用参与拼团按钮
    disableJoinButton() {
        const groupItem = this.element.closest('.group-buy-item');
        if (groupItem) {
            const joinBtn = groupItem.querySelector('.join-group-btn');
            if (joinBtn) {
                joinBtn.disabled = true;
                joinBtn.style.backgroundColor = '#ccc';
                joinBtn.style.cursor = 'not-allowed';
            }
        }
    }
}

// ==================== 初始化倒计时 ====================
let timers = [];

function initCountdowns() {
    // 清除旧的倒计时
    timers.forEach(timer => timer.stop());
    timers = [];

    const countdownElements = document.querySelectorAll('.countdown:not(.ended)');
    countdownElements.forEach(element => {
        const countdownStr = element.getAttribute('data-countdown');
        const index = parseInt(element.getAttribute('data-index'));

        // 只为有效的倒计时创建定时器
        if (countdownStr && countdownStr !== '已结束' && countdownStr !== '无效的时间') {
            const timer = new CountdownTimer(element, countdownStr, index);
            timers.push(timer);
        }
    });
}

// ==================== 事件绑定 ====================
function bindEvents() {
    // 参与拼团按钮点击事件
    document.addEventListener('click', async function(e) {
        if (e.target.classList.contains('join-group-btn') && !e.target.disabled) {
            e.preventDefault(); // 阻止默认行为

            const outTradeNo = e.target.getAttribute('data-out-trade-no');
            const teamId = e.target.getAttribute('data-team-id');

            // 需要登录才能参与拼团
            requireLogin(async (userId) => {
                console.log(`用户 ${userId} 正在参与拼团`);
                console.log(`outTradeNo: ${outTradeNo}, teamId: ${teamId}`);

                // 调用拼团下单接口，传入 teamId
                const orderData = await API.lockPayOrder(userId, {
                    outTradeNo: outTradeNo,
                    teamId: teamId
                });

                if (orderData) {
                    // 显示支付弹窗
                    PaymentModal.show(orderData.deductionPrice);
                }
            });
        }
    });

    // 单独购买按钮点击事件
    document.getElementById('buyAloneBtn').addEventListener('click', function(e) {
        e.preventDefault(); // 阻止默认行为

        // 需要登录才能购买
        requireLogin((userId) => {
            // 单独购买功能待实现
            showAlert('单独购买功能待实现');
        });
    });

    // 拼团购买按钮点击事件（发起新的拼团）
    document.getElementById('buyGroupBtn').addEventListener('click', async function(e) {
        e.preventDefault(); // 阻止默认行为

        // 需要登录才能拼团购买
        requireLogin(async (userId) => {
            console.log(`用户 ${userId} 正在发起新的拼团...`);

            // 调用拼团下单接口，不传 teamId（发起新拼团）
            const orderData = await API.lockPayOrder(userId, {});

            if (orderData) {
                // 显示支付弹窗
                PaymentModal.show(orderData.deductionPrice);
            }
        });
    });
}

// ==================== 支付弹窗管理 ====================
const PaymentModal = {
    modal: null,
    overlay: null,
    amountElement: null,

    // 初始化
    init() {
        this.modal = document.getElementById('paymentModal');
        this.overlay = document.getElementById('modalOverlay');
        this.amountElement = document.getElementById('paymentAmount');

        // 绑定关闭事件
        document.getElementById('cancelPaymentBtn').addEventListener('click', () => {
            this.close();
        });

        document.getElementById('confirmPaymentBtn').addEventListener('click', () => {
            this.handleConfirmPayment();
        });

        // 点击遮罩层关闭弹窗
        this.overlay.addEventListener('click', () => {
            this.close();
        });
    },

    // 显示弹窗
    show(amount) {
        this.amountElement.textContent = amount.toFixed(2);
        this.modal.classList.add('show');
        // 禁止页面滚动
        document.body.style.overflow = 'hidden';
    },

    // 关闭弹窗
    close() {
        this.modal.classList.remove('show');
        // 恢复页面滚动
        document.body.style.overflow = '';
        console.log('支付弹窗已关闭');
    },

    // 确认支付处理
    async handleConfirmPayment() {
        const amount = this.amountElement.textContent;
        const userId = LoginManager.getUserId();

        console.log(`用户 ${userId} 确认支付 ¥${amount} 外部交易单号 ${globalData.currentOrderInfo.outTradeNo}`);

        // 调用交易结算接口
        const settlementData = await API.settlementOrder();

        if (settlementData) {
            let statusMessage = '';

            // 解析订单状态
            if (settlementData.orderStatus === 1) {
                statusMessage += '订单已支付成功！\n';
            }

            // 解析拼团状态
            if (settlementData.groupBuyTeamStatus === 0) {
                statusMessage += '拼团中，等待其他成员加入';
            } else if (settlementData.groupBuyTeamStatus === 1) {
                statusMessage += '拼团成功！';
            }

            showAlert(statusMessage);
            this.close();

            // 刷新页面数据
            await loadAndRenderProductInfo();
        }
    }
};

// ==================== 页面加载完成后执行 ====================
let carousel;

document.addEventListener('DOMContentLoaded', async function() {
    // 1. 初始化轮播图
    carousel = new Carousel();

    // 2. 加载并渲染商品信息和团购列表（无论是否登录都可以浏览）
    await loadAndRenderProductInfo();

    // 3. 绑定事件（点击按钮时才检查登录状态）
    bindEvents();

    // 4. 初始化支付弹窗
    PaymentModal.init();
});

// 页面卸载时清理定时器
window.addEventListener('beforeunload', () => {
    if (carousel) {
        carousel.stopAutoPlay();
    }
    timers.forEach(timer => timer.stop());
});